package com.educhains.web.util;

import com.educhains.module.user.vo.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author YuRun
 * @since 2017年8月21日
 */
public class SessionUtils {
    /**
     * Save user into session
     *
     * @param request
     * @param user
     */
    public static void setUser(HttpServletRequest request, User user) {
        SessionUtils.setAttribute(request, User.USER_SESSION_KEY, user);
    }

    /**
     * Get user from session
     *
     * @param request
     * @return
     */
    public static User getUser(HttpServletRequest request) {
        return SessionUtils.getAttribute(request, User.USER_SESSION_KEY, User.class);
    }


    /**
     * Set value to session
     *
     * @param request
     * @param key
     * @param value
     */
    public static void setAttribute(HttpServletRequest request, String key, Object value) {
        request.getSession(true).setAttribute(key, value);
    }

    /**
     * Get attribute and not depend on concrete VO
     *
     * @param request
     * @param key
     * @param cls
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getAttribute(HttpServletRequest request, String key, Class<T> cls) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return null;
        }
        return (T) session.getAttribute(key);
    }

    /**
     * Remove session attribute by key
     *
     * @param request
     * @param key
     */
    public static void removeAttribute(HttpServletRequest request, String key) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute(key);
        }
    }

    /**
     * Invalidate session
     *
     * @param request
     */
    public static void invalidate(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }
}
